package game.module.ddz.processor;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.ddz.bean.DdzRound;
import game.module.ddz.logic.DdzDataManager;
import game.module.ddz.logic.DdzLogic;
import game.session.SessionManager;
import lion.common.ArrayUtility;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageDdz.C2SDdzQiangDiZhu;
import lua.LuaMessageDdz.PushDdzFaPai2;
import lua.LuaMessageDdz.PushDdzQiangDiZhu;
import lua.LuaMessageDdz.PushDiZhuSelect;
import lua.LuaMessageDdz.S2CDdzQiangDiZhu;
import lua.LuaMessageLogin.S2ErrorCode;

@MsgCodeAnn(msgcode = C2SDdzQiangDiZhu.id, accessLimit = 500)
public class DdzQiangDiZhuProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(DdzQiangDiZhuProcessor.class);

	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw request) throws Exception {
		C2SDdzQiangDiZhu reqMsg = C2SDdzQiangDiZhu.parse(request);
		int playerId = playingRole.getId();
		byte is_qiang = reqMsg.is_qiang;
		logger.info("ddz qiang dizhu,playerId={},is_qiang={}", playerId, is_qiang);
		// 房间是否存在
		DdzRound ddzRound = DdzDataManager.getInstance().getDdzRoom(playerId);
		if (ddzRound == null) {
			S2ErrorCode respMsg = new S2ErrorCode(201);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		// 房间类型是否正确
		if (ddzRound.getJiaoFenOrQiang() == 1) {
			S2ErrorCode respMsg = new S2ErrorCode(208);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		// 还有玩家没有准备好
		if(ddzRound.getConnectedPlayerIndexSet() == null || ddzRound.getConnectedPlayerIndexSet().size() < ddzRound.getPlayerIds().size()) {
			S2ErrorCode respMsg = new S2ErrorCode(215);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
//		// 已经有人反抢
//		if (ddzRound.getQiangDiZhuIndex() != null) {
//			S2ErrorCode respMsg = new S2ErrorCode(209);
//			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
//			return;
//		}
//		// do
//		int myIndex = ddzRound.getPlayerIds().indexOf(playerId);
//		// 处理
//		if (is_qiang == 1) {
//			ddzRound.setQiangDiZhuIndex(myIndex);
//			sendResp(playingRole, ddzRound, playerId, is_qiang);
//		} else {
//			sendResp(playingRole, ddzRound, playerId, is_qiang);
//			synchronized (ddzRound) {
//				// 是否没人抢地主
//				Set<Byte> cancelQiangSet = ddzRound.getCancelQiangSet();
//				if (cancelQiangSet == null) {
//					cancelQiangSet = new HashSet<>();
//					ddzRound.setCancelQiangSet(cancelQiangSet);
//				}
//				cancelQiangSet.add((byte) myIndex);
//				// 所有人都没有抢地主
//				if (cancelQiangSet.size() >= ddzRound.getPlayerIds().size()) {
//					reFaPai(ddzRound);
//				}
//			}
//		}
		//地主已经产生
		if(ddzRound.getDiZhuIndex() != null) {
			S2ErrorCode respMsg = new S2ErrorCode(211);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;
		}
		// do
		int myIndex = ddzRound.getPlayerIds().indexOf(playerId);
		// 处理
		if (is_qiang == 1) {
			sendResp(playingRole, ddzRound, playerId, is_qiang);
			selectDiZhu(ddzRound, myIndex, (short) 2);
		} else {
			sendResp(playingRole, ddzRound, playerId, is_qiang);
			synchronized (ddzRound) {
				// 是否没人抢地主
				Set<Byte> cancelQiangSet = ddzRound.getCancelQiangSet();
				if (cancelQiangSet == null) {
					cancelQiangSet = new HashSet<>();
					ddzRound.setCancelQiangSet(cancelQiangSet);
				}
				cancelQiangSet.add((byte) myIndex);
				// 所有人都没有抢地主
				if (cancelQiangSet.size() >= ddzRound.getPlayerIds().size()) {
					reFaPai(ddzRound);
				}
			}
		}		
	}
	
	private void selectDiZhu(DdzRound ddzRound, int myIndex, short jiaoScore) {
		ddzRound.setDiZhuIndex(myIndex);
		ddzRound.setChuPaiIndex(myIndex);
		ddzRound.setRoundScore(jiaoScore);
		// 推送消息
		PushDiZhuSelect pushDiZhuSelect = new PushDiZhuSelect((short) myIndex);
		List<Integer> playerIds = ddzRound.getPlayerIds();
		for (Integer aPlayerId : playerIds) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushDiZhuSelect.build(pr.alloc()));
			}
		}
	}

	private void sendResp(PlayingRole playingRole, DdzRound ddzRound, int playerId, byte is_qiang) {
		S2CDdzQiangDiZhu retMsg = new S2CDdzQiangDiZhu();
		playingRole.writeAndFlush(retMsg.build(playingRole.alloc()));
		// push
		int myIndex = ddzRound.getPlayerIds().indexOf(playerId);
		PushDdzQiangDiZhu pushMsg = new PushDdzQiangDiZhu((byte) myIndex, is_qiang);
		List<Integer> playerIds = ddzRound.getPlayerIds();
		for (Integer aPlayerId : playerIds) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushMsg.build(pr.alloc()));
			}
		}
	}

	/**
	 * 没人叫地主，重新发牌
	 * 
	 * @param ddzRound
	 */
	private void reFaPai(DdzRound ddzRound) {
		DdzLogic.getInstance().randCard(ddzRound);
		int jiaoDiZhuIndex = RandomUtils.nextInt(0, 3);
		ddzRound.setJiaoDiZhuIndex(jiaoDiZhuIndex);
		ddzRound.setLoopCount(0);
		ddzRound.setQiangDiZhuIndex(null);
		Set<Byte> cancelset = ddzRound.getCancelQiangSet();
		if (cancelset != null) {
			cancelset.clear();
		}
		PushDdzFaPai2 pushFaPai2 = new PushDdzFaPai2();
		pushFaPai2.di_cards = ArrayUtility.toByteArray(ddzRound.getDi());
		pushFaPai2.jiao_dizhu_index = (short) jiaoDiZhuIndex;
		List<Integer> playerIdList = ddzRound.getPlayerIds();
		int playerIndex = 0;
		for (Integer aPlayerId : playerIdList) {
			List<Byte> cardList = ddzRound.getCards().get(playerIndex++);
			pushFaPai2.my_cards = ArrayUtility.toByteArray(cardList);
			PlayingRole pr = SessionManager.getInstance().getPlayer(aPlayerId);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushFaPai2.build(pr.alloc()));
			}
		}
	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

}
